<template>
    <el-container class="org-admin">
        <el-aside width="320px">
            <el-scrollbar>
              <el-tree
                style="max-width: 600px"
                ref="treeRef"
                @node-click="handleNodeClick"
                :data="tree"
                :props="treeConfig" />
            </el-scrollbar>
        </el-aside>
        <el-container direction="vertical">
            <el-row>
                <el-col :span="24">
                    部门详情
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="部门代码:">
                        {{details.departmentCode}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="部门名称:">
                        {{details.departmentName}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="部门管理员:">
                        {{details.departmentManger}}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                </el-col>
                <el-col :span="8" v-if="control.create || control.delete || control.appoint">
                    <el-row justify="end">
                        <el-button v-if="control.create" type="default" @click="createUnit">创建...</el-button>
                        <el-button v-if="control.delete" type="default" @click="rmUnit">删除</el-button>
                        <el-button v-if="control.appoint" type="default" @click="appointUnitManager">任命...</el-button>
                    </el-row>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    部门角色
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-table :data="roles" tooltip-effect="dark" style="width: 100%">
                        <el-table-column 
                            prop="groupName" 
                            label="角色名称" 
                            width="150">
                        </el-table-column>
                        <el-table-column 
                            prop="groupDescirption" 
                            label="角色描述" 
                            width="450">
                        </el-table-column>
                        <el-table-column 
                            label="操作">
                            <template #default="scope">
                                <el-button @click="grantStaff(scope.row)" type="default">
                                    授权/撤销...
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
        </el-container>
    </el-container>

    <el-dialog
        v-model="dialog.create"
        title="创建子部门"
        width="40%"
        destroy-on-close>
        <el-form :model="addUnit"
            ref="addunitRef"
            :rules="addUnit_rules">
            <el-form-item label="部门代码:" prop="add_unit_departmentCode" label-width="140px">
                <el-input v-model="addUnit.add_unit_departmentCode" autocomplete="off" />
            </el-form-item>
            <el-form-item label="部门名称:" prop="add_unit_departmentName" label-width="140px">
                <el-input v-model="addUnit.add_unit_departmentName" autocomplete="off" />
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="createUnitSubmit">确定</el-button>
            <el-button @click="dialog.create = false">取 消</el-button>
        </span>
    </el-dialog>


    <el-dialog
        v-model="dialog.appoint"
        title="任命管理员"
        width="65%"
        destroy-on-close>
        <el-container direction="vertical">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="登录名:">
                        <el-input v-model="appoint.search" placeholder="请输入登录名" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="16">
                    <el-row justify="start">
                        <el-button type="primary" @click="searchUserList">搜索</el-button>
                    </el-row>
                </el-col>
            </el-row>
            <el-table :data="appoint.selectList"
                ref="staffTableRef"
                tooltip-effect="dark"
                highlight-current-row
                @current-change="handleCurrentChange"
                style="width:100%">
                <el-table-column
                    label="员工编号"
                    prop="staffId">
                </el-table-column>
                <el-table-column
                    label="员工帐号"
                    prop="resource.alias">
                </el-table-column>
            </el-table>
            <el-pagination background
                v-model:page-size="appoint.pageInfo.pageSize"
                layout="prev, pager, next"
                :current-page="appoint.pageInfo.current" 
                @current-change="currentChange"
                :pageCount="appoint.pageInfo.total%appoint.pageInfo.pageSize==0 ? 
                    appoint.pageInfo.total/appoint.pageInfo.pageSize : 
                    Math.floor(appoint.pageInfo.total/appoint.pageInfo.pageSize)+1" />
        </el-container>
        <span slot="footer" class="dialog-footer">
            <el-button @click="appointSubmit">确定</el-button>
            <el-button @click="dialog.appoint = false">取 消</el-button>
        </span>
    </el-dialog>


</template>
<script>
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
    data(){
        return {
            tree:[],
            details:{
                departmentId:'',
                departmentCode: '',
                departmentName: '',
                departmentManger:''
            },
            control: {
                create: false,
                delete: false,
                appoint: false
            },
            dialog:{
                create: false,
                appoint: false
            },
            roles:[],
            addUnit:{
                add_unit_departmentCode: '',
                add_unit_departmentName: '',
            },
            appoint:{
                search: "",
                selectList:[],
                pageInfo:{
                    current:1,
                    pageSize:5
                },
                unitManagerOriginId:'',
                unitManagerSelectedId:'',
            },
            addUnit_rules:{
                add_unit_departmentCode:[
                    {required: true, message:'请输入部门代码', trigger:'blur'},
                ],
                add_unit_departmentName:[
                    {required: true, message:'请输入部门名称', trigger:'blur'},
                ],
            },
            treeConfig:{
                children: 'children',
                label: 'label'
            }
        }
    },
    mounted(){
        /*** TODO ***/ 
        this.tree.push({
            id: 1000045,
            label: '联仓物联云平台',
            children:[]
        })
        this.axios.get("/backend/admin/unit/item2/1000045").then((r)=>{
            if(r.status === 200){
                this.details.departmentId = r.data.data.unit.resource.id
                this.details.departmentCode = r.data.data.unit.unitCode
                this.details.departmentName = r.data.data.unit.unitName
                this.details.departmentManger = r.data.data.person.englishName
                this.fillPage(r.data.data.unit);
            }
        })
    },
    methods: {
        handleNodeClick:function(node){
            this.axios.get("/backend/admin/org/children/" + node.id).then((r)=>{
                if(r.status === 200){
                    node.children = []
                    if(r.data.data!=null && r.data.data.length>0){
                        console.log("children size",r.data.data.length)
                        r.data.data.forEach((item)=>{
                            let _child = {}
                            _child.id= item.id
                            _child.label = item.name
                            _child.parentId = node.id
                            _child.children = []
                            console.log(_child)
                            node.children.push(_child)
                        })
                    }
                    this.axios.get("/backend/admin/unit/item2/"+node.id).then((r)=>{
                        if(r.status === 200){
                            this.details.departmentId = r.data.data.unit.resource.id
                            this.details.departmentCode = r.data.data.unit.unitCode
                            this.details.departmentName = r.data.data.unit.unitName
                            this.details.departmentManger = r.data.data.person.englishName
                            this.appoint.unitManagerOriginId = r.data.data.staff.resource.id
                            this.fillPage(r.data.data.unit)
                        }
                    })
                }
            });
        },
        createUnit:function(event){
            this.dialog.create = true
            this.addUnit.add_unit_departmentCode=''
            this.addUnit.add_unit_departmentName=''
        },
        createUnitSubmit(event){
            let form = this.$refs.addunitRef
            if(!form){
                return
            }
            form.validate((valid) => { 
                if (valid) {
                    this.axios({
                        url: "/backend/admin/org/unit/add/validate",
                        method: "post",
                        headers:{
                            "Content-Type":"application/x-www-form-urlencoded"
                        },
                        data:{
                            "unitResourceId": this.details.departmentId,
                            "departmentName": this.addUnit.add_unit_departmentName,
                            "departmentCode": this.addUnit.add_unit_departmentCode
                        }
                    }).then((r)=>{
                        if(r.status === 200 && r.data.status === 200 ){
                            this.axios({
                                url: "/backend/admin/org/unit/add",
                                method: "post",
                                headers:{
                                    "Content-Type":"application/x-www-form-urlencoded"
                                },
                                data:{
                                    "unitResourceId": this.details.departmentId,
                                    "departmentName": this.addUnit.add_unit_departmentName,
                                    "departmentCode": this.addUnit.add_unit_departmentCode
                                }
                            }).then((rr)=>{
                                if(rr.status === 200 && rr.data.status === 200){
                                    this.dialog.create = false
                                    let callfun = this.handleNodeClick
                                    let tree = this.$refs.treeRef
                                    let selected = tree.getCurrentNode()
                                    let callbackId = selected.id
                                    setTimeout(function(){
                                        console.log("refresh tree...")
                                        callfun({"id": callbackId})
                                    },500);
                                }   
                            })
                        }
                    })
                }
            })
        },
        rmUnit:function(event){
            ElMessageBox.confirm(
                '确认删除此单位?',
                'Warning',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                this.axios.get("/backend/admin/org/unit/remove/" + this.details.departmentId).then((r)=>{
                    if(r.status == 200 && r.data.status === 200){
                        let tree = this.$refs.treeRef
                        let selected = tree.getCurrentNode()
                        let parentId = selected.parentId
                        ElMessage({
                            type: 'success',
                            message: '删除部门成功',
                        })
                        let callfun = this.handleNodeClick
                        let callbackId = parentId
                        setTimeout(function(){
                            tree.remove(selected)
                            callfun({"id": callbackId})
                        },100)
                    }
                })
                
            }).catch(() => {
            })
        },
        appointUnitManager:function(event){
            this.dialog.appoint = true
            this.appoint.selectList = []
            this.appoint.pageInfo.current = 1
            this.searchUserList()
        },
        currentChange: function(value){
            this.appoint.pageInfo.current = value
            this.searchUserList()
        },
        searchUserList:function(){
            let queryParam= {"pageInfo": this.appoint.pageInfo,"alias": this.appoint.search,"order":{"columnName":"","sortValue":""}}
            this.axios.post("/backend/staff/paging",queryParam).then((r)=>{ 
                if(r.status === 200 && r.data.status === 200){
                    this.appoint.selectList = r.data.data.list
                    this.appoint.pageInfo = r.data.data.pageInfo
                    let table = this.$refs.staffTableRef
                    setTimeout(()=>{
                        table.data.forEach((item,idx)=>{
                            if(item.resource.id == this.appoint.unitManagerOriginId){
                                table.setCurrentRow(item)
                            }
                        })  
                    },200);
                }
            })
        },
        handleCurrentChange:function(v){
            this.appoint.unitManagerSelectedId = v.resource.id
            console.log(this.appoint.unitManagerSelectedId)
        },
        appointSubmit:function(){
            if(this.appoint.unitManagerSelectedId  == this.appoint.unitManagerOriginId){
                ElMessage({
                    type: 'error',
                    message: '管理员没有改变',
                })
            }else{
                //let node = {"id": this.details.unitResourceId}
                //let callback = this.handleNodeClick;
                this.axios.get("/backend/admin/org/unit/appoint/"+ this.details.departmentId + "/" + this.appoint.unitManagerSelectedId).then((r)=>{
                    if(r.status == 200){
                        ElMessage({
                            type: 'success',
                            message: '新管理员任命成功',
                        })
                        this.dialog.appoint = false
                        //setTimeout(()=>{
                        //    callback(node)
                        //},500)
                    }
                })
                
            }


        },
        grantStaff:function(roleItem){

        },
        fillPage:function(unit){
            this.axios.post("/backend/frontend/resource",{"parentId":unit.context$3.id,"alias":"children"})
                .then((rr)=>{
                    this.axios.get("/backend/frontend/resource/id/permission/"+rr.data.data.id +"/write")
                        .then((rrr)=>{
                            if(rrr.status === 200 && rrr.data.status === 200) {
                                this.control.create = true
                            }else{
                                this.control.create = false
                            }
                        })
                })
            
            this.axios.get("/backend/frontend/resource/id/permission/"+unit.resource.id +"/write")
                .then((rr)=>{
                    if(rr.status === 200 &&  rr.data.status === 200){
                        this.control.delete = true
                        this.control.appoint = true
                    }else{
                        this.control.delete = false
                        this.control.appoint = false
                    }
                });
            
            this.axios.post("/backend/frontend/resource",{"parentId":unit.context$3.id,"alias":"group"})
                .then((rr)=>{
                    if(rr.status === 200 && rr.data.data.children) {
                        this.roles = []
                        rr.data.data.children.forEach((item)=>{
                            this.axios.post("/backend/frontend/resource",{"id":item.id})
                                .then((rrr)=>{ 
                                    if(rrr.status === 200 &&  rrr.data.status === 200) {
                                        let groupItem = {}
                                        groupItem.id= item.id
                                        groupItem.groupName= rrr.data.data.object.groupName
                                        groupItem.groupDescirption = rrr.data.data.object.groupDescirption
                                        this.roles.push(groupItem)
                                    }
                                })
                        })
                    }
                });
        }
    }
}
</script>
<style scoped>
</style>